package cn.gz.ibix.library.loader;

import com.google.common.collect.Lists;
import com.google.common.reflect.TypeToken;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import cn.gz.ibix.library.http.IConvertResponse;
import cn.gz.ibix.library.http.IHttpUtil;
import cn.gz.ibix.library.http.RequestParam;
import lombok.Getter;
import lombok.Setter;

/**
 * 项目名称：QiYiChuAPP
 * <br>类描述：
 * <br>创建人：htliu
 * <br>创建时间：2018/3/24 18:19
 * <br>修改人:
 * <br>修改时间：2018/3/24 18:19
 * <br>修改备注：
 * <br>@version
 */
public abstract class BaseDataLoader<T> {
    //    private static final Handler uiHandler = new Handler(Looper.getMainLooper());
    protected final String TAG = getClass().getSimpleName();
    private final Object LOCK = new Object();
    protected int pageSize = 10;
    protected int page = 0;
    @Getter
    @Setter
    protected int total = 0;
    @Setter
    protected Listener listener;
    @Getter
    protected boolean loading = false;
    protected Class<T> handleClazz;
    @Getter
    protected boolean end = false;
    @Getter
    private List<T> list = Lists.newArrayList();

    public BaseDataLoader() {
        TypeToken<T> type = new TypeToken<T>(getClass()) {
        };
        handleClazz = (Class<T>) type.getRawType();
    }

    public void load() {
        load(new HashMap<String, String>());
    }

    public void load(Map<String, String> params) {
        params.put("page", String.valueOf(page + 1));
        params.put("pageSize", String.valueOf(pageSize));
        RequestParam<T> requestParam = getRequestParam();
        requestParam.api(api())
                .params(params)
                .iConvertResponse(getConvertResponse());
        getHttpUtil().request(requestParam);

    }

    protected void loadSuccess(int currentPage, int total, List<T> dataList) {
        synchronized (LOCK) {
            end = dataList.isEmpty();
            if (page == 0) {
                this.list.clear();
            }
            this.page = currentPage;
            this.total = total;
            list.addAll(dataList);
            loading = false;
        }
        this.listener.onSuccess();
    }

    protected RequestParam<T> getRequestParam() {
        return new RequestParam<T>();
    }

    protected abstract IHttpUtil getHttpUtil();

    protected abstract IConvertResponse<T> getConvertResponse();

    protected abstract String api();

}
